package com.drs.challenge.tool;

import com.drs.challenge.ChallengeApplication;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import com.google.zxing.client.j2se.MatrixToImageWriter;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author Jasmine-drs
 * @date 2023/7/6 9:16
 */

@Slf4j
public class QRCodeGenerator {

	/**
	 * 生成二维码
	 *
	 * @param text  二维码内容
	 * @param width 二维码宽度
	 * @param height    二维码高度
	 * @return  二维码字节数组
	 */
	public static byte[] generateQRCode(String text, int width, int height) throws WriterException {
//		String jarPath = new File(ChallengeApplication.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getParentFile().getPath();
		String jarPath = System.getProperty("user.dir");
		String imgDir = jarPath + "\\static\\img\\";
		log.debug("imgDir = " + imgDir);
		File file = new File(imgDir);
		if(!file.exists()){
			file.mkdirs();
		}
		String name = text.substring(text.lastIndexOf("id=")+3);

		// 生成二维码
		BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height);
		// 二维码输出流
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		Path path = Paths.get(imgDir + name + ".png");  // 使用Path对象代表图片路径
		try {
//			 二维码写入文件
			MatrixToImageWriter.writeToPath(bitMatrix, "png", path);
			// 二维码写入流转换
			MatrixToImageWriter.writeToStream(bitMatrix, "png", outputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return outputStream.toByteArray();
	}
}
